const permissionService = require('../service/permission.service')
const { OPERATION_IS_NOT_ALLOWED } = require('../config/error')
const verifyPermission = async (ctx, next) => {
	// 1.拿到用户id 和contentid
	const { id } = ctx.user
	// 2.获取资源的名称 / id
	const keyName = Object.keys(ctx.params)[0]
	const resourceId = ctx.params[keyName]
	const resourceName = keyName.replace('Id', '')

	// 2.查询用户user 的 id 是否有修改momentId的权限
	const isPermission = await permissionService.checkResouce(
		resourceName,
		resourceId,
		id
	)
	if (!isPermission) {
		return ctx.app.emit('error', OPERATION_IS_NOT_ALLOWED, ctx)
	}
	await next()
}

// 判断是不是管理管理员或者社长
const verifyAdmin = async (ctx, next) => {
	const { id } = ctx.user
	const { club_id } = ctx.params
	console.log(id, club_id)
	// 判断是否是 Admin
	const isAdmin = await permissionService.checkAdmin(id)
	const isLeader = await permissionService.checkClubLeader(id, club_id)
	console.log(isLeader)
	console.log(isAdmin)
	if (!isLeader && !isAdmin) {
		return ctx.app.emit('error', OPERATION_IS_NOT_ALLOWED, ctx)
	}

	await next()
}

// 判断有没有删除当前帖子的权限
const verifyOperatePost = async (ctx, next) => {
	const { id } = ctx.user
	const { post_id } = ctx.params
	// 判断是否为管理员
	const isAdmin = await permissionService.checkAdmin(id)
	// 判断这个帖子是不是他自己的
	const isOwner = await permissionService.checkPostBelong(id, post_id)
	if (!isAdmin && !isOwner) {
		return ctx.app.emit('error', OPERATION_IS_NOT_ALLOWED, ctx)
	}
	await next()
}

// 判断角色是不是超管
const verifyAdminOnly = async (ctx, next) => {
	const { id } = ctx.user
	// 判断是否是 Admin
	const isAdmin = await permissionService.checkAdmin(id)
	if (!isAdmin) {
		return ctx.app.emit('error', OPERATION_IS_NOT_ALLOWED, ctx)
	}
	await next()
}

module.exports = {
	verifyPermission,
	verifyAdmin,
	verifyOperatePost,
	verifyAdminOnly
}
